#include "HttpClients/HttpHeader.hpp"
#include <boost/algorithm/string.hpp>

using namespace CppWinApi::HttpClients;

HttpHeader::HttpHeader()
{
    curlHeaders = nullptr;
    headerIsChanged = true;
    headers = {{"Content-Type", "application/json"}};
}

std::string &HttpHeader::operator[](const std::string &key)
{
    std::lock_guard<std::mutex> lock(objLock);
    std::string normalizedKey = boost::algorithm::to_lower_copy(key);
    headerIsChanged = true;
    return headers[normalizedKey];
}

void HttpHeader::Remove(const std::string &key)
{
    std::lock_guard<std::mutex> lock(objLock);
    std::string normalizedKey = boost::algorithm::to_lower_copy(key);
    headers.erase(normalizedKey);
    headerIsChanged = true;
}

curl_slist *HttpHeader::ToCurlHeaders()
{
    std::lock_guard<std::mutex> lock(objLock);
    if (!headerIsChanged)
        return curlHeaders.get();

    curl_slist* newList = nullptr;

    for (const auto &[key, value] : headers)
    {
        newList = curl_slist_append(newList, (key + ": " + value).c_str());
        if (!newList)
            throw std::bad_alloc();
    }

    // 重新设置表头指针
    curlHeaders.reset(newList);
    headerIsChanged = false;
    return curlHeaders.get();
}